package com.taskflow.service;

import com.taskflow.common.PageResult;
import com.taskflow.dto.EntryQueryDTO;
import com.taskflow.entity.EntryData;
import com.taskflow.mapper.EntryDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关单数据Service
 */
@Service
public class EntryDataService {

    @Autowired
    private EntryDataMapper entryDataMapper;

    public void saveEntryData(EntryData entryData) {
        // 拼接费率字段（在其他处理之前）
        // feeRate = feeCurr/feeRate/feeMark
        if (entryData.getFeeCurr() != null || entryData.getFeeRate() != null || entryData.getFeeMark() != null) {
            String feeCurr = entryData.getFeeCurr() != null ? entryData.getFeeCurr() : "";
            String feeRate = entryData.getFeeRate() != null ? entryData.getFeeRate() : "";
            String feeMark = entryData.getFeeMark() != null ? entryData.getFeeMark() : "";
            entryData.setFeeRate(feeCurr + "/" + feeRate + "/" + feeMark);
        }
        
        // insurRate = insurCurr/insurRate/insurMark
        if (entryData.getInsurCurr() != null || entryData.getInsurRate() != null || entryData.getInsurMark() != null) {
            String insurCurr = entryData.getInsurCurr() != null ? entryData.getInsurCurr() : "";
            String insurRate = entryData.getInsurRate() != null ? entryData.getInsurRate() : "";
            String insurMark = entryData.getInsurMark() != null ? entryData.getInsurMark() : "";
            entryData.setInsurRate(insurCurr + "/" + insurRate + "/" + insurMark);
        }
        
        // otherRate = otherCurr/otherRate/otherMark
        if (entryData.getOtherCurr() != null || entryData.getOtherRate() != null || entryData.getOtherMark() != null) {
            String otherCurr = entryData.getOtherCurr() != null ? entryData.getOtherCurr() : "";
            String otherRate = entryData.getOtherRate() != null ? entryData.getOtherRate() : "";
            String otherMark = entryData.getOtherMark() != null ? entryData.getOtherMark() : "";
            entryData.setOtherRate(otherCurr + "/" + otherRate + "/" + otherMark);
        }
        
        // 自动填充海关名称和口岸名称
        if (entryData.getCustomMaster() != null && !entryData.getCustomMaster().isEmpty()) {
            String customMasterName = entryDataMapper.getCustomsNameByCode(entryData.getCustomMaster());
            if (customMasterName != null) {
                entryData.setCustomMasterName(customMasterName);
            }
        }
        
        if (entryData.getIePort() != null && !entryData.getIePort().isEmpty()) {
            String iePortName = entryDataMapper.getCustomsNameByCode(entryData.getIePort());
            if (iePortName != null) {
                entryData.setIePortName(iePortName);
            }
        }
        
        // 自动填充运输方式名称
        if (entryData.getTrafMode() != null && !entryData.getTrafMode().isEmpty()) {
            String trafModeName = entryDataMapper.getTransfNameByCode(entryData.getTrafMode());
            if (trafModeName != null) {
                entryData.setTrafModeName(trafModeName);
            }
        }
        
        // 自动填充贸易方式名称
        if (entryData.getTradeMode() != null && !entryData.getTradeMode().isEmpty()) {
            String tradeModeName = entryDataMapper.getTradeNameByCode(entryData.getTradeMode());
            if (tradeModeName != null) {
                entryData.setTradeModeName(tradeModeName);
            }
        }
        
        // 1. 自动填充征免性质名称
        if (entryData.getCutMode() != null && !entryData.getCutMode().isEmpty()) {
            String cutName = entryDataMapper.getCutNameByCode(entryData.getCutMode());
            if (cutName != null) {
                entryData.setCutName(cutName);
            }
        }
        
        // 2. 自动填充贸易国家名称
        if (entryData.getTradeCountry() != null && !entryData.getTradeCountry().isEmpty()) {
            String tradeCountryName = entryDataMapper.getTradeCountryNameByCode(entryData.getTradeCountry());
            if (tradeCountryName != null) {
                entryData.setTradeCountryName(tradeCountryName);
            }
        }
        
        // 3. 自动填充成交币制名称
        if (entryData.getTradeCurr() != null && !entryData.getTradeCurr().isEmpty()) {
            String tradeCurrName = entryDataMapper.getTradeCurrNameByCode(entryData.getTradeCurr());
            if (tradeCurrName != null) {
                entryData.setTradeCurrName(tradeCurrName);
            }
        }
        
        // 4. 自动填充成交方式名称
        if (entryData.getTransMode() != null && !entryData.getTransMode().isEmpty()) {
            String transModeName = entryDataMapper.getTransModeNameByCode(entryData.getTransMode());
            if (transModeName != null) {
                entryData.setTransModeName(transModeName);
            }
        }
        
        // 5. 自动填充包装种类名称
        if (entryData.getWrapType() != null && !entryData.getWrapType().isEmpty()) {
            String wrapTypeName = entryDataMapper.getWrapTypeNameByCode(entryData.getWrapType());
            if (wrapTypeName != null) {
                entryData.setWrapTypeName(wrapTypeName);
            }
        }
        
        // 6. 自动填充贸易国名称
        if (entryData.getTradeAreaCode() != null && !entryData.getTradeAreaCode().isEmpty()) {
            String tradeAreaName = entryDataMapper.getTradeAreaNameByCode(entryData.getTradeAreaCode());
            if (tradeAreaName != null) {
                entryData.setTradeAreaName(tradeAreaName);
            }
        }
        
        // 7. 自动填充原产国名称
        if (entryData.getOriginCountry() != null && !entryData.getOriginCountry().isEmpty()) {
            String originCountryName = entryDataMapper.getOriginCountryNameByCode(entryData.getOriginCountry());
            if (originCountryName != null) {
                entryData.setOriginCountryName(originCountryName);
            }
        }
        if (entryData.getDestinationCountry() != null && !entryData.getDestinationCountry().isEmpty()) {
            String destinationCountryName = entryDataMapper.getOriginCountryNameByCode(entryData.getDestinationCountry());
            if (destinationCountryName != null) {
                entryData.setDestinationCountryName(destinationCountryName);
            }
        }

        // 8. 自动填充装货港名称
        if (entryData.getDistinatePort() != null && !entryData.getDistinatePort().isEmpty()) {
            String distinatePortName = entryDataMapper.getDistinatePortNameByCode(entryData.getDistinatePort());
            if (distinatePortName != null) {
                entryData.setDistinatePortName(distinatePortName);
            }
        }
        
        // 9. 自动填充境内目的地名称
        if (entryData.getDistrictCode() != null && !entryData.getDistrictCode().isEmpty()) {
            String districtName = entryDataMapper.getDistrictNameByCode(entryData.getDistrictCode());
            if (districtName != null) {
                entryData.setDistrictName(districtName);
            }
        }
        
        // 9.5. 自动填充入境口岸/离境口岸名称
        if (entryData.getEntryPortCode() != null && !entryData.getEntryPortCode().isEmpty()) {
            String entryPortName = entryDataMapper.getEntryPortNameByCode(entryData.getEntryPortCode());
            if (entryPortName != null) {
                entryData.setEntryPortName(entryPortName);
            }
        }
        
        // 10. 自动填充征免方式名称
        if (entryData.getDutyMode() != null && !entryData.getDutyMode().isEmpty()) {
            String dutyModeName = entryDataMapper.getDutyModeNameByCode(entryData.getDutyMode());
            if (dutyModeName != null) {
                entryData.setDutyModeName(dutyModeName);
            }
        }
        
        // 11. 将单位代码替换为单位名称
        // qty1Unit
        if (entryData.getQty1Unit() != null && !entryData.getQty1Unit().isEmpty()) {
            String unitName = entryDataMapper.getUnitNameByCode(entryData.getQty1Unit());
            if (unitName != null) {
                entryData.setQty1Unit(unitName);
            }
        }
        
        // qty2Unit
        if (entryData.getQty2Unit() != null && !entryData.getQty2Unit().isEmpty()) {
            String unitName = entryDataMapper.getUnitNameByCode(entryData.getQty2Unit());
            if (unitName != null) {
                entryData.setQty2Unit(unitName);
            }
        }
        
        // qtyUnit
        if (entryData.getQtyUnit() != null && !entryData.getQtyUnit().isEmpty()) {
            String unitName = entryDataMapper.getUnitNameByCode(entryData.getQtyUnit());
            if (unitName != null) {
                entryData.setQtyUnit(unitName);
            }
        }
        
        entryDataMapper.insert(entryData);
    }

    public EntryData getByEntryId(String entryId) {
        return entryDataMapper.selectByEntryId(entryId);
    }

    /**
     * 获取关单数据详情（包含所有明细）
     */
    public List<EntryData> getByEntryIdWithDetails(String entryId) {
        return entryDataMapper.selectByEntryIdWithDetails(entryId);
    }

    public PageResult<EntryData> getEntryDataList(EntryQueryDTO query) {
        List<EntryData> list = entryDataMapper.selectList(query);
        Long total = entryDataMapper.selectCount(query);
        return new PageResult<>(list, total, query.getCurrent(), query.getSize());
    }

    public boolean existsByEntryId(String entryId) {
        return entryDataMapper.existsByEntryId(entryId);
    }

    /**
     * 检查关单明细是否存在（entryId + gNo 联合主键）
     */
    public boolean existsByEntryIdAndGNo(String entryId, String gNo) {
        return entryDataMapper.existsByEntryIdAndGNo(entryId, gNo);
    }

    /**
     * 根据任务条件查询关单数据
     * @param declareDateRange 申报日期范围（天数）：1/5/10/15/20/30
     */
    public List<EntryData> getByTaskConditions(String companyName, String companyTaxNo, String entryId, Integer declareDateRange) {
        // 计算申报日期范围
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String declareDateEnd = sdf.format(calendar.getTime()); // 今天
        
        // 往前推 N 天
        if (declareDateRange != null && declareDateRange > 0) {
            calendar.add(Calendar.DAY_OF_MONTH, -declareDateRange);
        } else {
            calendar.add(Calendar.DAY_OF_MONTH, -1); // 默认前1天
        }
        String declareDateStart = sdf.format(calendar.getTime());
        
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("companyName", companyName);
        conditions.put("companyTaxNo", companyTaxNo);
        conditions.put("entryId", entryId);
        conditions.put("declareDateStart", declareDateStart);
        conditions.put("declareDateEnd", declareDateEnd);
        
        return entryDataMapper.selectByTaskConditions(conditions);
    }
}

